package com.pc.tas.learning.trace.index;

import com.pc.cloud.services.SearchServices;
import com.pc.tas.learning.trace.Trace;
import com.pc.tas.learning.trace.TraceService;
import com.pc.tas.util.SpringBeanUtil;
import org.apache.commons.lang.time.DateUtils;

import java.util.Collection;
import java.util.Date;

public class TraceIndexManager {
	private static TraceIndexManager tiManager;
	private TraceIndexManager(){		
	}	
	
	public synchronized static TraceIndexManager getInstance() {
		if(tiManager == null) {
			tiManager = new TraceIndexManager();
		}
		
		return tiManager;
	}
	
	public void indexTrace(Date beginOn,Date endOn) throws Exception {
		String beginOnStr = TraceSearchFields.dayDateFormat.format(beginOn);
		String endOnStr = TraceSearchFields.dayDateFormat.format(endOn);	
		this.indexTrace(beginOnStr, endOnStr);		
	}
	
	public void indexTrace(String beginOn,String endOn) throws Exception {
long a = System.currentTimeMillis();		
		String flag = beginOn;
		SearchServices sss = (SearchServices) SpringBeanUtil.getBean("searchServices");
		while(endOn.compareTo(flag) >=0) {
			try {
				System.out.println(flag);
				TraceService ts = TraceService.getInstance();
				
				int i = 0;
				int n =1000;
				Collection<Trace> traces= ts.getPage(flag, i, n);
				while(traces.size() >0) {
	System.out.println(i);				
					TraceDocumentBuilder builder = new TraceDocumentBuilder(traces);
					sss.index(builder);
					i = i + n;
					traces = ts.getPage(flag,i, n);
					
				}
	System.out.println(i);			
	long b = System.currentTimeMillis();
	System.out.println("cost : " + (b-a) + "ms");

				
		
			}catch(Exception e) {
				e.printStackTrace();
			} finally {
				flag = TraceSearchFields.dayDateFormat.format(DateUtils.addDays(TraceSearchFields.dayDateFormat.parse(flag),1));
			}
	}
	}
}
